<template>
  <div class="container flex-col">
    <div class="flex-row-center space-between">
      <span class="page_title">题库列表</span>
      <div>
        <el-button :icon="Plus" @click="btn_click_create_qt" class="btn_top" type="primary"
                   style="background-color: #3F8CFF ;color: white;">
          新建
        </el-button>
        <el-button class="btn_top" link>
          导入
        </el-button>

        <el-button class="btn_top" link>
          保存
        </el-button>

        <el-button class="btn_top" link>
          取消
        </el-button>
      </div>
    </div>
    <div class="flex_1 flex-col comm_border" style="margin-top: 16px;">
      <div class="flex-row-center " style="margin: 8px 24px auto 24px;">
        <div class="flex_1 flex-row-center">
          <div class="search_title">题目类型</div>
          <el-select v-model="data.selectQtType" size="large" style="margin-left: 16px; width: 200px"
                     placeholder="类型">
            <el-option
                v-for="(qtType, index) in listQtType"
                :key="index"
                :label="qtType.value"
                :value="qtType.key"
            ></el-option>
          </el-select>
          <div class="search_title" style="margin-left: 32px;">时间</div>
          <el-date-picker style="margin-left: 16px; width: 150px"
                          type="date"
                          placeholder="请输入日期"
                          value-format="YYYY-MM-DD"
                          format="YYYY-MM-DD"
                          size="large"></el-date-picker>
          <div class="search_title" style="margin-left: 16px;">至</div>
          <el-date-picker type="date"
                          placeholder="请输入日期"
                          value-format="YYYY-MM-DD"
                          format="YYYY-MM-DD" style="margin-left: 16px; width: 150px"
                          size="large"></el-date-picker>
          <div class="search_title" style="margin-left: 32px;">题目</div>
          <el-input placeholder="请输入题目" size="large"
                    style="margin-left: 32px;flex:auto;max-width: 200px;"></el-input>

        </div>
        <el-button size="large" style="width: 100px;" type="primary" class="search_btn_primary" @click="click_search">搜索
        </el-button>
      </div>
      <div class="flex_1" style="margin: 16px 16px auto">
        <el-table :data="data.listQtBank" border :row-class-name="tableRowClassName">
          <el-table-column prop="index" label="序号" width="60"/>
          <el-table-column prop="title" label="题目"/>
          <el-table-column prop="" label="标签" width="150"/>
          <el-table-column prop="score" label="分值" width="80"/>
          <el-table-column prop="creatorName" label="创建人" width="120"/>
          <el-table-column prop="createTimeStr" label="创建时间" width="180"/>
          <el-table-column label="操作" width="150px">
            <template #default="scope">
              <el-button link size="small" @click="click_preview(scope.$index, scope.row)">查看
              </el-button>
              <el-button size="small"
                         type="danger"
                         @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex-row-reverse-center" style="height: 50px;">
        <el-pagination
            v-model:current-page="pager.currentPage"
            v-model:page-size="pager.pageSize"
            :page-sizes="[10,20,50,100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pager.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">

import {Plus} from "@element-plus/icons-vue";
import {onMounted, reactive, shallowRef} from "vue";
import {IntString} from "@/type/dto/KeyValue";
import {ExamType_Naire} from "@/constants/Constants_ExamType";
import {api_question_bank_delete, api_question_bank_list} from "@/request/apis/qtApi";
import {QtBankVO} from "@/type/vo/QtBankVO";
import {ElMessage, ElNotification} from "element-plus";
import {addDialog} from "@/components/gDialog/index";
import QtPreview from "@/views/Naire/dialogs/NaireQtPreview.vue";
import QtCreate from "@/views/Naire/dialogs/NaireQtCreate.vue";
import {tickAsTimeString} from "@/utils/TimeUtil";
import QtEdit from "@/views/Naire/dialogs/NaireQtEdit.vue";
import msg from "@/components/msg";
import {ListQtTypeInfo} from "@/constants/Constants_ListQtTypeInfo";


const data = reactive({
  dtStart: '',
  dtEnd: '',
  searchName: '',
  searchTag: '',
  selectQtType: 0,
  listQtBank: Array<QtBankVO>(),
  ansCount: 10,
})
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 10,
})
const listQtType = reactive(ListQtTypeInfo);
const dialogData = reactive({
  showCreateQtDialogFlag: false,
  formData: {},
})

const click_search = () => {
  pager.currentPage = 1;
  search_pri();
}

const click_preview = (index: number, row: QtBankVO) => {
  // 调起来预览
  console.log('row', row);
  try {
    addDialog({
      title: "预览题目",
      component: shallowRef(QtPreview),
      width: "600px",
      props: {
        qbId: row.qbId
      },
      callBack: (goEdit: boolean) => {
        if (goEdit) {
          addDialog({
            title: "编辑题目",
            component: shallowRef(QtEdit),
            width: "800px",
            props: {
              qbId: row.qbId
            },
            callBack: async (result2: Boolean) => {
              if (result2) {
                ElMessage.success('修改成功!');
                await search_pri();
              } else {
              }
              console.log(data, "data")
            }
          })


        } else {
          // tableList.data[index as number] = data
        }
        console.log(data, "data")
      }
    })
    // 处理确认操作
  } catch (error) {
    // 处理取消操作
  }
}
const handleDelete = async (index: number, row: QtBankVO) => {
  console.log(index, row)
  const r = await msg.yesNo(`是否确认删除 ${row.title}?`);
  if (r) {
    const r = await api_question_bank_delete(row.qbId);
    if (!r) {
      await msg.error("获取数据异常!");
      return;
    }
    if (r.code != 0) {
      await msg.error(`获取数据异常!  ${r.code} msg：${r.msg}`);
      return;
    }
    ElNotification({
      title: '提示',
      message: '已删除!',
    })
    await search_pri();
  }
}

onMounted(async () => {
  await search_pri();
})

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  search_pri();
}

const search_pri = async () => {
  data.listQtBank.length = 0;
  const startDate = data.dtStart ? data.dtStart : '';
  const questionTag = data.searchTag;
  const endDate = data.dtEnd ? data.dtEnd : '';
  const page = pager.currentPage;
  const limit = pager.pageSize;
  const examType = ExamType_Naire;
  const questionName = data.searchName;
  let queryType = null;
  if (data.selectQtType > 0) {
    queryType = data.selectQtType;
  }
  const r = await api_question_bank_list(startDate,
      endDate,
      questionName,
      questionTag,
      queryType,
      examType, page, limit);
  if (!r) {
    await msg.error('数据异常!');
    return;
  }
  if (r.code != 0) {
    await msg.error(`错误! ${r.code}${r.msg}`);
    return;
  }
  if (r.data.records) {
    for (let i = 0; i < r.data.records.length; i++) {
      r.data.records[i].index = i + 1;
      r.data.records[i].createTimeStr = tickAsTimeString(r.data.records[i].createTime)
    }
  }

  data.listQtBank = r.data.records;
  pager.total = r.data.total;
}

const handleCurrentChange = (val: number) => {
  search_pri();
}

interface User {
  date: string
  name: string
  address: string
}

const tableRowClassName = ({
                             row,
                             rowIndex,
                           }: {
  row: User
  rowIndex: number
}) => {
  if (rowIndex === 1) {
    return 'warning-row'
  } else if (rowIndex === 3) {
    return 'success-row'
  }
  return ''
}


async function btn_click_create_qt() {
  try {
    addDialog({
      title: "创建题目",
      component: shallowRef(QtCreate),
      width: "800px",
      props: {},
      callBack: async (goEdit: Boolean) => {
        if (goEdit) {
          ElMessage.success('创建成功!');
          await search_pri();
        } else {
          // tableList.data[index as number] = data
        }
        console.log(data, "data")
      }
    })
    // 处理确认操作
  } catch (error) {
    // 处理取消操作
  }
}
</script>

<style scoped>
.btn_top {
  border: none;
  height: 48px;
  padding: 13px 28px;
  background-color: white;
  border-radius: 12px;
  color: #3F8CFF;
  font-size: 16px;
  font-weight: 400;
}


.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

</style>